package com.by.log.example;


import com.by.log.LoggerFactory;
import com.by.log.RpcLogContext;
import com.by.log.filter.RpcTraceFilter;
import com.by.log.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * 分布式追踪使用示例
 * 展示如何在RPC调用中使用分布式追踪功能
 */
public class DistributedTraceExample {
    private static final Logger log = LoggerFactory.getLogger(DistributedTraceExample.class);
    
    public static void main(String[] args) {
        // 模拟服务A调用服务B的场景
        serviceACallServiceB();
    }
    
    /**
     * 服务A调用服务B
     */
    private static void serviceACallServiceB() {
        // 服务A开始处理请求
        log.info("Service A started processing request");
        
        // 模拟RPC调用前的准备
        Map<String, String> headers = new HashMap<>();
        RpcLogContext rpcContext = RpcTraceFilter.beforeInvoke(headers);
        rpcContext.setServiceName("ServiceA");
        rpcContext.setMethodName("callServiceB");
        
        try {
            // 模拟服务A调用服务B
            log.info("Service A calling Service B");
            serviceBProcess();
            
            log.info("Service A completed request successfully");
        } catch (Exception e) {
            log.error(e, "Service A failed to process request");
        } finally {
            // 清理追踪上下文
            RpcTraceFilter.afterInvoke();
        }
    }
    
    /**
     * 服务B处理请求
     */
    private static void serviceBProcess() {
        // 创建子跨度
        RpcLogContext childContext = RpcTraceFilter.createChildSpan("ServiceB", "processRequest");
        
        try {
            log.info("Service B started processing request");
            
            // 模拟业务处理
            Thread.sleep(100);
            
            // 记录方法调用统计
            log.recordMethodCall(true, 100);
            
            log.info("Service B completed request successfully");
        } catch (Exception e) {
            log.error(e, "Service B failed to process request");
            log.recordMethodCall(false, 100);
        }
    }
}